use thiserror::Error;
use super::api;
use super::capability::ThreadSafeCapability;

// 定义CPU错误类型
#[derive(Error, Debug)]
pub enum CpuError {
    #[error("CPU time slice allocation failed")]
    TimeSliceFailed,
    
    #[error("Invalid CPU capability")]
    InvalidCapability,
    
    #[error("Invalid time slice value")]
    InvalidTimeSlice,
}

// 定义CPU结果类型
pub type CpuResult<T> = Result<T, CpuError>;

// CPU管理器
pub struct CpuManager {
    capability: ThreadSafeCapability,
}

impl CpuManager {
    // 创建新的CPU管理器
    pub fn new(capability: ThreadSafeCapability) -> CpuResult<Self> {
        // 验证能力是否为CPU类型
        if let Ok(cap) = capability.lock() {
            if cap.resource_type() != super::super::core::types::ResourceType::Cpu {
                return Err(CpuError::InvalidCapability);
            }
        } else {
            return Err(CpuError::InvalidCapability);
        }
        
        Ok(CpuManager {
            capability,
        })
    }
    
    // 获取CPU时间片
    pub fn get_time_slice(&self, milliseconds: u32) -> CpuResult<bool> {
        // 验证时间片值是否有效
        if milliseconds == 0 {
            return Err(CpuError::InvalidTimeSlice);
        }
        
        // 获取能力ID
        let cap_id = if let Ok(cap) = self.capability.lock() {
            cap.id()
        } else {
            return Err(CpuError::TimeSliceFailed);
        };
        
        // 调用FFI获取CPU时间片
        let result = unsafe {
            api::exokernel_get_cpu_time_slice(cap_id, milliseconds)
        };
        
        if result {
            Ok(true)
        } else {
            Err(CpuError::TimeSliceFailed)
        }
    }
}